<?php
// +----------------------------------------------------------------------
// | 中犇单商户
// +----------------------------------------------------------------------
// | Copyright (c) 2019-2021 中犇科技 All rights reserved.
// +----------------------------------------------------------------------


namespace app\api\controller\v1;

use app\api\controller\Base;
use app\user\model\User;
use app\user\model\MoneyLog;
use app\user\model\Withdraw as WithdrawModel;
use app\user\model\WithdrawAccount;
use think\Db;
use service\ApiReturn;
use think\helper\Hash;
use think\response\Json;

/**
 * 余额以及积分接口
 * Class Money
 * @package app\api\controller
 * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
 * @since 2019/4/23 19:33
 */
class Money extends Base
{
    /**
     * 我的余额
     * @return void
     * @since 2019/4/23 18:21
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    public function get_my_money($data = [], $user = [])
    {
        $money = \think\Db::name('user')->where('id', $user['id'])->find();
        $money['min_withdraw_money'] = module_config('user.min_withdraw_money');
        $money['withdraw_handling_type'] = module_config('user.withdraw_handling_type');
        $money['withdraw_handling_fee'] = module_config('user.withdraw_handling_fee');
        $money['total_revenue_money'] = bcadd($money['user_money'], $money['freeze_money'], 2);   //用户总金额=用户余额+冻结金额
        $money['freeze_money_rule'] = module_config('user.freeze_money_rule');  //冻结金额规则显示
        //分享赚-暂时屏蔽
        $money['share_money'] = Db::name("user_money_log")->where([
            'user_id' => $user['id'],
            'change_type' => 8
        ])->sum("change_money");
        //自购返-暂时屏蔽
        $money['discounts_money'] = 0;
        //可提现余额
        $money['money'] = $money['user_money'];

        return ApiReturn::r(1, $this->filter($money, $this->fname), lang('请求成功'));
    }

    /**
     * 获取余额交易明细
     * @return void
     * @throws DbException
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @since 2019/4/23 18:30
     */
    public function get_money_detail($data = [], $user = [])
    {
        $change_type = $data['change_type'] ? intval($data['change_type']) : 0;
       $where = [];
        if ($data['date']) {
            $start_time = strtotime($data['date']);
            $end_time = strtotime('+1 month', $start_time);
            $where[] = ["create_time", "BETWEEN", [$start_time,$end_time]];  
        }
        if ($data['start_data'] && $data['end_data']) {
            $start_time = strtotime($data['start_data']);
            $end_time = strtotime($data['end_data'] . " 23:59:59");
            $where[] = ["create_time", "BETWEEN", [$start_time,$end_time]];
        }
        
        if ($change_type) {
            switch ($change_type) {
                //充值记录
                case 1:
                    $where[] = ['change_type', 'in', '1,3'];
                    $where[] = ["change_money", ">", 0];
                    break;
                //消费明细
                case 2:
                    $where[] = ['change_type', 'in', '2,4,5,6,7,8,9,10'];
                    $where[] = ["change_money", "<", 0];
                    break;
                //收入记录
                case 3:
                    $where[] =  ["change_money", ">", 0];
                    break;
                //支出记录
                case 4:
                    $where[] = ["change_money", "<", 0];
                    break;              
                default:            
                    break;
            }
        }
        $lists = MoneyLog::where($where)
            ->where('user_id', $user['id'])    
            ->where($where)
            ->order('aid', 'desc')
            ->paginate()
            ->each(function ($item) {
               $item['check_reason'] = '';              
               if (floatval($item['change_money']) > 0) {
                   $item['t'] = 1;
               } else {
                   $item['t'] = 2;
               }     
               return $item;
           });
        return ApiReturn::r(1, $lists, lang('请求成功'));
    }

    /**
     * 上传微信或支付宝提现账号信息
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/9/13 20:46
     */
    public function bind_withdraw_account($data, $user)
    {
        $data['user_id'] = $user['id'];
        $WithdrawAccount = new \app\user\model\WithdrawAccount();
        $info = $WithdrawAccount->where(['user_id' => $user['id'], 'account_type' => $data['account_type']])->find();
        // 启动事务
        Db::startTrans();
        try {
            if (empty($data['account_id'])) {
                exception(lang('绑定账号不能为空'));
            }
            if ($info) {
                $res1 = $WithdrawAccount->where(['user_id' => $user['id']])->update(['is_default' => 0, 'update_time' => time()]);
                $data['update_time'] = time();
                $res = $WithdrawAccount->where(['user_id' => $user['id'], 'account_type' => $data['account_type']])->update($data);
                if ($res === false || $res1 == false) {
                    exception(lang('绑定失败'));
                }
            } else {
                $data['status'] = 1;
                $res = $WithdrawAccount->create($data);
                if (!$res) {
                    exception(lang('绑定失败'));
                }
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ApiReturn::r(0, [], $e->getMessage());
        }
        $info = $WithdrawAccount->where(['user_id' => $user['id'], 'account_type' => $data['account_type']])->find();
        return ApiReturn::r(1, $info, lang('绑定成功'));
    }

    /**
     * 获取绑定的提现账号
     * @param $data
     * @param $user
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/9/13 21:39
     */
    public function get_withdraw_account($data, $user)
    {
        $res = WithdrawAccount::where(['user_id' => $user['id'], 'account_type' => $data['account_type']])->find();

        if ($res) {
            if ($res['status'] == 1) {
                if ($data['account_type'] != 3 && $res['qrcode'] == '') {
                    return ApiReturn::r(0, [], lang('暂未绑定'));
                }
            } else {
                return ApiReturn::r(0, [], lang('暂未绑定'));
            }
        } else {
            return ApiReturn::r(0, [], lang('暂未绑定'));
        }
        $result = $this->filter($res, $this->fname);
        return ApiReturn::r(1, $result, lang('请求成功'));
    }

    /**
     * 申请提现
     * @return Json
     * @since 2019/4/23 19:05
     * @editor 李志豪 [ 995562569@qq.com ]
     * @updated 2019.05.21
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    public function withdraw($data = [], $user = [])
    {
      
        $money = $data['money'];
        $type = $data['type'];
        $userInfo = User::get($user['id']);
        if (empty($userInfo['pay_password'])) {
            return ApiReturn::r(1001, [], lang('请设置支付密码'));
        }
        $_type = 2;
        $time = strtotime(date("Y-m-d"));
        $_where[] = ['user_id', '=', $user['id']];
        $_where[] = ['time', 'gt', $time];
        $_where[] = ['type', '=', $_type];

        $count = Db::name('user_login_info')->where($_where)->count();
        if ( !Hash::check($data['pay_password'], $userInfo['pay_password'])) {
            $now_time = time();
            Db::name('user_login_info')->insert([
                'mobile' => $user['mobile'],
                'time' => $now_time,
                'user_id' => $user['id'],
                'type' => $_type
            ]);
            if ($count >= module_config("user.pay_count")) {
                return ApiReturn::r(0, [], '账号支付密码已被锁定,请明天再试');
            } else {
                return ApiReturn::r(1002, [], lang('支付密码错误'));
            }
        }
        // 启动事务
        Db::startTrans();
        try {
            //申请
            WithdrawModel::addInfo($userInfo, $money, $type);           
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ApiReturn::r(0, [], $e->getMessage());
        }
        return ApiReturn::r(1, [], lang('申请提现成功'));
    }

    /**
     * 获取充值规则
     * @param $data
     * @param $user
     * @return \think\response\Json
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/5/8 18:49
     */
    public function recharge_rule($data, $user)
    {
        $list = \app\user\model\RechargeRule::where("status", 1)
//            ->where('group', $data['group'])
            ->order("sort asc,id asc")->select();
        $info = [];
        foreach ($list as $val) {
            $info[] = $this->filter($val, $this->fname);
        }
        return ApiReturn::r(1, $info, lang('成功'));
    }


    /**
     * 获取提现记录
     * @param  [type] $data [description]
     * @param  [type] $user [description]
     * @return [type]       [description]
     */
    public function get_withdraw_list($data, $user)
    {       
        $page_size = $data['list_rows'] ?? 10;
        
        $map[] = ["user_id","=",$user["id"]];
        if ($data['start_data'] && $data['end_data']) {
            $start_time = strtotime($data['start_data']);
            $end_time = strtotime($data['end_data'] . " 23:59:59");
            $map[] = ["create_time","BETWEEN",[$start_time,$end_time]];
        }
        $paginate = WithdrawModel::where($map)->order("create_time desc")->paginate($page_size);
        $list = $paginate->items();
        foreach($list as &$item){
            if ($item['cash_status'] == 1) {
                $item['check_status'] = 3;
            } elseif ($item['cash_status'] == 2) {
                $item['check_status'] = 4;
            }            
        }    
        return ApiReturn::r(1, ['list' => $list, 'count' => $paginate->total(), 'last_page' => $paginate->lastPage()], lang('成功'));
    }

    /**
     * 获取提现规则
     * @param  [type] $data [description]
     * @param  [type] $user [description]
     * @return [type]       [description]
     */
    public function withdraw_rule($data, $user)
    {
        $list = Db::name('user_withdraw_rule')->where('status', 1)->order('sort asc')->select();
        return ApiReturn::r(1, $list, lang('成功'));
    }
}
